<template>
  <div id="contianer">
    <div>
      <el-form
        ref="uploadForm"
        :model="uploadForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="附件上传" prop="fileId">
          <preview-upload
            :showPreviewButton="true"
            :showDownloadButton="false"
            :showDeleteButton="true"
            :multiple="true"
            :isOnly="false"
            :acceptType="acceptType"
            :fileSize="fileSize"
            uploadUrl="/knowledgeFile/file/upload"
            paramsName="files"
            :accessoryList="filesArr"
            :before-upload="startFakeProgress"
            :on-success="uploadSuccess"
            :on-error="handleUploadError"
            @getValue="getAccessoryList"
          ></preview-upload>
        </el-form-item>
      </el-form>
      <!-- 线形进度条 -->
      <div v-if="progressVisible" class="linear-progress-container">
          <div class="linear-progress-info">
              <span class="linear-progress-filename">{{ progressFileName }}</span>
              <span class="linear-progress-percentage">{{ Math.round(progressPercentage) }}%</span>
          </div>
          <el-progress 
              :percentage="Math.round(progressPercentage)" 
              :stroke-width="6"
              :show-text="false"
              status="success"
          ></el-progress>
      </div>
    </div>

    <div class="button_group">
      <el-button
        :disabled="
          !uploadAllow ||
          filesArr.length === 0 ||
          (beforeFileList && beforeFileList.length > 0)
        "
        type="primary"
        @click="importFn"
        >导入</el-button
      >
    </div>
  </div>
</template>
<script>
import PreviewUpload from "@/components/accessory/PreviewUploadFile";
export default {
  data() {
    return {
      dialogVisible: false,
      loading: false,
      loadingAddButton: false,
      acceptType: "",
      fileSize: "",
      uploadForm: {
        majorType: "",
        knowType: "",
        fileId: "",
      },
      uploadAllow: true,
      rules: {
        majorType: [
          { required: true, message: "请选择专业类型", trigger: "change" },
        ],
        knowType: [
          { required: true, message: "请选择知识类型", trigger: "change" },
        ],
        fileId: [
          { required: true, message: "上传文件不能为空", trigger: "change" },
        ],
      },
      filesArr: [],
      beforeFileList: [],
      // 进度条相关
      progressVisible: false,
      progressPercentage: 0,
      progressFileName: '',
      progressTimer: null,
      currentUploadFile: null
    };
  },
  components: {
    PreviewUpload,
  },
  created() {
    // // 这里处理文件的大小及类型显示
    // this.fileSize = 2 * 1024 * 1024 * 1024; // 1 GB
    // if ([31, 32].includes(this.$route.query.fileType)) {
    //   this.acceptType = ".doc,.docx,.pdf";
    // }
    // if ([33, 34].includes(this.$route.query.fileType)) {
    //   this.acceptType = ".xls,.xlsx,.pdf";
    // }
    // if (this.$route.query.fileType == 38) {
    //   this.acceptType = ".avi,.mp4,.wmv,.mov";
    //   this.fileSize = 3 * 1024 * 1024 * 1024;
    // }
  },
  mounted() {
    // if(this.$route.query.fileType == 38){
    //   this.acceptType = ".avi,.mp4,.wmv,.mov"
    // }else{
    //   this.acceptType = ".doc,.docx,.ppt,.pptx,.pdf,.xls,.xlsx"
    // }
  },
  methods: {
    // 附件
    getAccessoryList(val, beforeFileList) {
      this.filesArr = val;
      this.beforeFileList = beforeFileList;
      let uploadStatusError = val.findIndex((item) => item.uploadStatus === 1);
      if (uploadStatusError === -1) {
        this.uploadAllow = true;
      } else {
        this.uploadAllow = false;
      }
    },
    importFn() {
      this.$http({
        url: "/knowledgeFile/file/save",
        method: "post",
        data: this.filesArr,
      }).then(({ data }) => {
        console.log("data", data);
        if (data.code == 200) {
          this.$message.success("导入成功");
          this.$router.push("/knowledgeManage/originalFile");
        }
      });
    },
    handleUploadError: function(response, file, fileList) {
      this.loading = false
      // 停止进度条并显示失败
      this.stopFakeProgress(false)
    },
    uploadSuccess(res, file, fileList) {
      this.loading = false
      // 停止进度条并显示成功
      this.stopFakeProgress(true)
    },
     // 开始模拟进度条
    startFakeProgress(file) {
      console.log("🚀 ~ file-----:", file)
      this.progressFileName = file.name || '准备上传...';
      this.progressPercentage = 0;
      this.currentUploadFile = file;
      
      // 显示进度条
      this.progressVisible = true;
      
      // 根据文件大小动态计算动画时间（基于实际测试数据）
      const fileSize = file.size || 0;
      
      // 基于测试数据的计算：300MB约需2分钟(120000毫秒)
      // 计算上传速度基准：300MB / 120000ms = 0.0025 MB/ms
      const baseUploadSpeed = 0.0016; // MB/ms
      
      // 计算文件大小（MB）
      const fileSizeMB = fileSize / (1024 * 1024);
      
      // 基础时间计算
      let totalTime = fileSizeMB / baseUploadSpeed;
      
      // 确保小文件有合理的最小时间（至少3秒）
      totalTime = Math.max(totalTime, 3000);
      
      // 针对中文件的微调（10-50MB）- 基于13MB约20秒的测试数据
      if (fileSizeMB > 10 && fileSizeMB <= 50) {
        // 线性调整，确保13MB文件显示约20秒
        const adjustmentFactor = 0.8;
        totalTime = totalTime * adjustmentFactor;
      }
      
      // 对于超大文件（>2GB），应用递减因子避免时间过长
      if (fileSizeMB > 2000) {
        // 随着文件变大，时间增长逐渐放缓
        const largeFileFactor = 0.9 + (fileSizeMB / 10000); // 最大约1.1的因子
        totalTime = totalTime * largeFileFactor;
      }
      
      // 添加一些随机波动，让进度看起来更自然（±5%）
      const randomFactor = 0.95 + Math.random() * 0.1;
      totalTime = totalTime * randomFactor;
      
      console.log(`文件大小: ${(fileSizeMB).toFixed(2)}MB, 计算动画时间: ${(totalTime/1000).toFixed(2)}秒`);
      
      const step = 95 / (totalTime / 100); // 每100ms增加的进度，最多到95%
      
      // 清除之前的定时器
      if (this.progressTimer) {
        clearInterval(this.progressTimer);
      }
      
      // 设置新的定时器
      this.progressTimer = setInterval(() => {
        if (this.progressPercentage < 95) {
          this.progressPercentage += step;
          if (this.progressPercentage > 95) {
            this.progressPercentage = 95;
          }
        }
      }, 100);
    },
    
    // 停止进度条
    stopFakeProgress(isSuccess) {
      // 清除定时器
      if (this.progressTimer) {
        clearInterval(this.progressTimer);
        this.progressTimer = null;
      }
      
      // 设置进度为100%
      this.progressPercentage = 100;
      
      // 延迟隐藏进度条
      setTimeout(() => {
        this.progressVisible = false;
        this.progressPercentage = 0;
        this.currentUploadFile = null;
      }, isSuccess ? 500 : 1500);
    },
    
  },
};
</script>
<style lang="scss" scoped>
#contianer {
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 50px 50px 20px;
  .button_group {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #d8d8d8;
    text-align: center;
  }
}
</style>
